/**
 * 路由入口
 */
import fs from "fs";
import { rootDir, apiPrefix } from "@root/config";

const routersDir: string = `${rootDir}\\router\\routers`;
function addMapping(router: any, mapping: any) {
    for (let url in mapping) {
        if(url.includes(" ")){
            let urlMap = url.split(" ");
            let method = urlMap[0];
            let path = urlMap[1] || "/";
            let upMethod = method.toUpperCase();
            if ('GET' === upMethod) {
                router.get(path, mapping[url]);
                console.log(`Router  GET: ${apiPrefix + path}`);
            } else if ('POST' === upMethod) {
                router.post(path, mapping[url]);
                console.log(`Router POST: ${apiPrefix + path}`);
            } else {
                console.log(`invalid URL: ${url}`);
            }
        }else{
            console.log(`invalid URL: ${url}`);
        }

        // if (url.startsWith('GET ')) {
        //     let path = url.substring(4);
        //     router.get(path, mapping[url]);
        //     console.log(`Router  GET: ${apiPrefix + path}`);
        // } else if (url.startsWith('POST ')) {
        //     let path = url.substring(5);
        //     router.post(path, mapping[url]);
        //     console.log(`Router POST: ${apiPrefix + path}`);
        // } else {
        //     console.log(`invalid URL: ${apiPrefix + url}`);
        // }
    }
}

function addControllers(router: any) {
    let files = fs.readdirSync(routersDir);
    let jsFiles = files.filter((file: string) => {
        return file.endsWith('.ts') || file.endsWith('.js');
    });
    for (let file of jsFiles) {
        let mapping = require(`${routersDir}\\${file}`);
        // console.log(mapping)
        addMapping(router, mapping);
    }
}
const creatRouter = function (){
    const koaRouter = require('koa-router')();
    koaRouter.prefix(apiPrefix);
    addControllers(koaRouter);
    return koaRouter;
}

export default creatRouter;
module.exports = creatRouter;
